/*
 * Copyright 2011 Michele Mancioppi [michele.mancioppi@gmail.com]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cave.nice.testMessage.templates;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class TemplateManager {

	public enum TemplateType {
		CONFIGURATIONS_FORWARD, CONFIGURATIONS_PROCMAILRC, CONFIRMATION_REGISTRATION, TEST_MESSAGE
	}

	private final VelocityEngine engine;

	public synchronized final static TemplateManager getInstance(ServletContext servletContext) {
		return new TemplateManager(servletContext);
	}

	private TemplateManager(ServletContext servletContext) {
		engine = new VelocityEngine();
		engine.setProperty("resource.loader", "webapp");
		engine.setProperty("webapp.resource.loader.class", "org.apache.velocity.tools.view.WebappResourceLoader");
		engine.setProperty("webapp.resource.loader.path", "/WEB-INF/templates/");
		engine.setApplicationAttribute("javax.servlet.ServletContext", servletContext);
	}

	public String applyTemplate(TemplateType type, Map<String, Object> parameters) throws TemplateException {
		String templateName = null;
		switch (type) {
		case CONFIGURATIONS_FORWARD: {
			templateName = "forward.vtl";
			break;
		}
		case CONFIGURATIONS_PROCMAILRC: {
			templateName = "procmailrc.vtl";
			break;
		}
		case CONFIRMATION_REGISTRATION: {
			templateName = "confirmRegistration.vtl";
			break;
		}
		case TEST_MESSAGE: {
			templateName = "testMessage.vtl";
			break;
		}
		default:
			throw new TemplateException("Unknown template type: " + type);
		}

		VelocityContext context = new VelocityContext(parameters);
		StringWriter sw = new StringWriter();
		try {
			engine.getTemplate(templateName).merge(context, sw);
			return sw.toString();
		} catch (Exception e) {
			throw new TemplateException("Error while applying the template: " + templateName, e);
		} finally {
			try {
				sw.close();
			} catch (IOException e) {
				/*
				 * TODO Log this?
				 */
			}
		}
	}

}
